﻿import axios from 'axios'
// import router from '../router'
import { Message, MessageBox } from 'element-ui'
// import {message} from './resetMessage';
import store from '../store'
import { getToken, setToken } from '@/utils/auth'

let has306err = false
// 创建axios实例
const service = axios.create({
	baseURL: process.env.BASE_API+"/api", // api 的 base_url
	timeout: 10000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(
	config => {
		var token = store.getters.token || getToken()
		if (token) {
			/* switch (config.method) {
				case 'get':
					if (!config.params) {
						config.params = {}
					}
					config.params.token = token
					break
				case 'post':
					// config.data.token = token;
					break
				default:
					break
			} */
			config.headers['Authorization'] = token
		}
		return config
	},
	error => {
		// Do something with request error
		console.log(error) // for debug
		Promise.reject(error)
	}
)

// response 拦截器
service.interceptors.response.use(
	response => {
		// console.log('response: ', response);
		let res = response.data
		if (typeof res === 'string') {
			try {
				res = JSON.parse(res)
			} catch (e) {
				console.log(e)
			}
		}
		var type = ''
		if (res.code !== 200) {
			type = 'error';
			if (type === "error") {
				Message({
					message: res.message,
					type,
					duration: 3.5 * 1000,
					dangerouslyUseHTMLString: true
				})
			}
		}
		//		拦截时间信息
		if (res.date && typeof res.date === 'string') {
			// console.log('res: ', res);
			const currentTime = res.date.slice(0, 10)
			store.dispatch&&store.dispatch('SetDateTime', currentTime)
		}
		return res
	},
	error => {
		switch (error.response.status) {
			case 500:
				Message({
					message: "网络连接异常，请重试。",
					type: "warning",
					duration: 3 * 1000,
					dangerouslyUseHTMLString: true
				})
				break;
			case 306:
				if (!has306err) {
					MessageBox.alert('账号在别处登录，您已被迫下线！', {
						title: '温馨提示',
						showClose: false,
						confirmButtonText: '确定',
						callback: action => {
							setToken('')
							has306err = false
							window.location.reload();
						}
					})
					has306err = true
				}
				break
			case 401:
				MessageBox.alert('用户登录已失效，请重新登录！', {
					title: '温馨提示',
					showClose: false,
					confirmButtonText: '确定',
					callback: action => {
						setToken('')
						window.location.reload();
					}
				})
				break
			default:
				break
		}

		return Promise.reject(error)
	}
)

export default service
